package com.xbongbong.parent.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasListGroupEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.util.ElasticSearchConditionUtil;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.SharePermissionHelp;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.DepartmentVO;
import com.xbongbong.paas.toolbox.wrap.RoleSimpleVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.parent.interfaces.ParentPermissionHandle;
import com.xbongbong.parent.pojo.GroupConditionPoJo;
import com.xbongbong.parent.pojo.list.ConditionListPojo;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.teammembers.enums.TeamEditBusinessEnum;
import com.xbongbong.pro.formdata.pojo.dto.FormDataDetailDTO;
import com.xbongbong.pro.permission.pojo.dto.VerifyUpdatePermissionDTO;
import com.xbongbong.pro.permission.pojo.dto.VerifyViewPermissionDTO;
import com.xbongbong.pro.statistic.result.pojo.ElasticAggsPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.enums.WorkOrderTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.DistributorContactEnum;
import com.xbongbong.saas.enums.business.ExpenseEnum;
import com.xbongbong.saas.enums.business.FundTransferEnum;
import com.xbongbong.saas.enums.business.OtherExpenseEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ReimbursementFormEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.subform.ProductTeamEnum;
import com.xbongbong.saas.enums.subform.SubFormTransferEnum;
import com.xbongbong.saas.model.CommunicatePlanUserModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.WorkOrderCcModel;
import com.xbongbong.saas.model.WorkOrderFlowNodeModel;
import com.xbongbong.saas.model.WorkOrderFlowUserModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.model.WorkReportApprovePeopleModel;
import com.xbongbong.saas.model.WorkReportCcModel;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.DataPermissionEnum;
import com.xbongbong.sys.enums.RoleEnum;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.util.AddressUtil;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.join.query.HasChildQueryBuilder;
import org.elasticsearch.join.query.JoinQueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * saas和paas业务的数据权限校验（团队）
 *  迁移自com.xbongbong.saas.help.SaasDetailPermissionHelp#checkPermission
 *  和 com.xbongbong.paas.help.PaasDetailPermissionHelp#checkPermission
 */
@Component
public class CommonPermissionHelp implements ParentPermissionHandle {

    @Resource
    private UserModel userModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private WorkReportCcModel workReportCcModel;
    @Resource
    private WorkOrderCcModel workOrderCcModel;
    @Resource
    private WorkOrderFlowNodeModel workOrderFlowNodeModel;
    @Resource
    private WorkOrderFlowUserModel workOrderFlowUserModel;
    @Resource
    private CommunicatePlanUserModel communicatePlanUserModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private WorkReportApprovePeopleModel workReportApprovePeopleModel;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private PublicGroupHelp publicGroupHelp;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private ProPermissionHelp proPermissionHelp;
    @Resource
    private SharePermissionHelp sharePermissionHelp;

    @Override
    public boolean checkPermission(VerifyViewPermissionDTO verifyViewPermissionDTO) throws XbbException {
        UserVO loginUser = verifyViewPermissionDTO.getLoginUser();
        PaasFormDataEntityExt paasFormDataEntityExt = verifyViewPermissionDTO.getPaasFormDataEntityExt();
        //整合之后防止有地方查出表单数据没有saasMark的，标记一下（调用的地方都有补充该参数）
        if(Objects.isNull(paasFormDataEntityExt.getSaasMark()) || Objects.isNull(paasFormDataEntityExt.getBusinessType())){
            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(paasFormDataEntityExt.getFormId(), paasFormDataEntityExt.getCorpid());
            paasFormDataEntityExt.setSaasMark(paasFormEntityExt.getSaasMark());
            paasFormDataEntityExt.setBusinessType(paasFormEntityExt.getBusinessType());
        }
        if (Objects.equals(SaasMarkEnum.SAAS.getCode(), paasFormDataEntityExt.getSaasMark())) {
            return saasCheckPermission(paasFormDataEntityExt, loginUser, loginUser.getDepSet(), paasFormDataEntityExt.getBusinessType());
        } else {
            return paasCheckPermission(loginUser, paasFormDataEntityExt.getId(), paasFormDataEntityExt.getMenuId());
        }
    }

    @Override
    public boolean checkPermission(VerifyUpdatePermissionDTO verifyUpdatePermissionDTO) throws XbbException {
        return checkPermission(new VerifyViewPermissionDTO(verifyUpdatePermissionDTO.getLoginUser(), verifyUpdatePermissionDTO.getPaasFormDataEntityExt()));
    }

    @Override
    public boolean checkViewPermission(VerifyViewPermissionDTO verifyViewPermissionDTO) throws XbbException {
        return checkPermission(verifyViewPermissionDTO) || sharePermissionHelp.verifySharePermission4QueryWithRuleEngine(verifyViewPermissionDTO);
    }

    @Override
    public boolean checkEditPermission(FormDataDetailDTO formDataDetailDTO, VerifyUpdatePermissionDTO verifyUpdatePermissionDTO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        Integer businessType = formDataDetailDTO.getBusinessType();
        //有团队校验团队可编辑权限&共享可编辑权限,没有团队校验通用权限&共享可编辑权限
        if (TeamEditBusinessEnum.getAllBusinessType().contains(businessType)) {
            return userTeamHelp.teamMembersCheckEditPermission(formDataDetailDTO, explainMap) || sharePermissionHelp.verifySharePermission4EditWithRuleEngine(verifyUpdatePermissionDTO);
        } else {
            return checkEditPermissionWithoutTeamEdit(verifyUpdatePermissionDTO);
        }
    }

    @Override
    public boolean checkEditPermissionWithoutTeamEdit(VerifyUpdatePermissionDTO verifyUpdatePermissionDTO) throws XbbException {
        //通用权限&共享可编辑权限
        return checkPermission(verifyUpdatePermissionDTO) || sharePermissionHelp.verifySharePermission4EditWithRuleEngine(verifyUpdatePermissionDTO);
    }

    @Override
    public boolean checkEditPermissionWithoutShareEdit(FormDataDetailDTO formDataDetailDTO, VerifyViewPermissionDTO verifyViewPermissionDTO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        Integer businessType = formDataDetailDTO.getBusinessType();
        //有团队校验团队可编辑权限&共享可见权限,没有团队校验通用权限&共享可见权限
        if (TeamEditBusinessEnum.getAllBusinessType().contains(businessType)) {
            return userTeamHelp.teamMembersCheckEditPermission(formDataDetailDTO, explainMap) || sharePermissionHelp.verifySharePermission4QueryWithRuleEngine(verifyViewPermissionDTO);
        } else {
            return checkPermission(verifyViewPermissionDTO) || sharePermissionHelp.verifySharePermission4QueryWithRuleEngine(verifyViewPermissionDTO);
        }
    }

    private boolean saasCheckPermission(PaasFormDataEntityExt paasFormDataEntityExt, UserVO userVO, Set<DepartmentVO> depSet, Integer businessType) throws XbbException {
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(userVO, userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.getByCode(paasFormDataEntityExt.getSaasMark()), paasFormDataEntityExt.getBusinessType(), paasFormDataEntityExt.getMenuId());
        if (Objects.equals(dataPermission, DataPermissionEnum.ALL.getCode()) || userVO.isAdminOrBoss()){
            return true;
        }
        Long dataId = paasFormDataEntityExt.getId();

        List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, userVO.getUserId(), userVO.getCorpid(), BasicConstant.ZERO,false);
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        BoolQueryBuilder boolQueryBuilder;
        String corpid = userEntity.getCorpid();
        switch (xbbRefTypeEnum){
            case CONTACT:
                Long customerId = paasFormDataEntityExt.getData().getLong(ContactEnum.CUSTOMER_NAME.getAttr());
                if (Objects.nonNull(customerId)) {
                    CustomerEntityExt customerEntityExt = customerModel.getByKey(customerId, paasFormDataEntityExt.getCorpid());
                    if (Objects.nonNull(customerEntityExt) && Objects.equals(customerEntityExt.getDel(), DelEnum.NORMAL.getDel())) {
                        Integer isPublic = customerEntityExt.getData().getInteger(CustomerManagementEnum.IS_PUBLIC.getAttr());
                        if (Objects.equals(isPublic, 1)) {
                            // 联系人，如果他关联的客户是公海客户，那么就不校验团队
                            return true;
                        }
                    }
                }
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_CONTACT_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case DISTRIBUTOR_CONTACT:
                Long distributorId = paasFormDataEntityExt.getData().getLong(DistributorContactEnum.DISTRIBUTOR_NAME.getAttr());
                if (Objects.nonNull(distributorId)) {
                    CustomerEntityExt customerEntityExt = customerModel.getByKey(distributorId, paasFormDataEntityExt.getCorpid());
                    if (Objects.nonNull(customerEntityExt) && Objects.equals(customerEntityExt.getDel(),DelEnum.NORMAL.getDel())) {
                        Integer isPublic = customerEntityExt.getData().getInteger(CustomerManagementEnum.IS_PUBLIC.getAttr());
                        if (Objects.equals(isPublic, 1)) {
                            // 联系人，如果他关联的客户是公海客户，那么就不校验团队
                            return true;
                        }
                    }
                }
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_CONTACT_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case CUSTOMER_MANAGEMENT:
                if (Objects.equals(paasFormDataEntityExt.getDel(),DelEnum.DELETE.getDel())){
                    //回收站客户就不区分了
                    return true;
                }
                if (Objects.equals(paasFormDataEntityExt.getData().getInteger(CustomerManagementEnum.IS_PUBLIC.getAttr()),1)){
                    //低权限公海校验
                    return publicCustomerCheck(userEntity,dataId,paasFormDataEntityExt.getFormId(),businessType);
                }
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_CUSTOMER_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case CLUE:
                if (Objects.equals(paasFormDataEntityExt.getDel(),DelEnum.DELETE.getDel())){
                    //回收站线索就不区分了
                    return true;
                }
                if (Objects.equals(paasFormDataEntityExt.getData().getInteger(ClueEnum.IS_PUBLIC.getAttr()),1)){
                    //低权限公海校验
                    return publicCustomerCheck(userEntity,dataId,paasFormDataEntityExt.getFormId(),businessType);
                }
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_CLUE_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case DISTRIBUTOR_MANAGEMENT:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_CUSTOMER_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case CONTRACT:
            case ORDER:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_CONTRACT_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case SALES_OPPORTUNITY:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_OPPORTUNITY_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case QUOTATION:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_QUOTATION_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case REFUND:
            case RETURN:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_REFUND_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case PAYMENT:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case PAY_PLAN:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case SUPPLIER:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case SUPPLIER_CONTACT:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case PURCHASE:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case BOM_BILL:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_BOM_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case PRODUCTION_ORDER:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case PAYMENT_SHEET:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case PAY_SHEET:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case MARKET_ACTIVITY:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case PAYMENT_TASK:
                boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, IndexTypeEnum.IDX_SAAS_PAYMENT_TASK_TEAM);
                return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
            case INVOICE:
            case PURCHASE_INVOICE:
            case RETURNED_PURCHASE:
            case ASSEMBLE:
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case TRANSFER:
            case INVENTORY:
            case CUSTOMER_COMMUNICATE:
                return checkPermissionByUserId(paasFormDataEntityExt,userIdIn,businessType);
            case OTHER_EXPENSE:
            case OTHER_INCOME:
            case FUND_TRANSFER:
                return checkPermissionByBelongId(paasFormDataEntityExt,userIdIn,businessType);
            case SUPPLIER_COMMUNICATE:
            case CUSTOMER_STATEMENT_STATISTIC:
            case DISTRIBUTOR_COMMUNICATE:
            case DISTRIBUTOR_ACCOUNT:
                return true;
//                return checkPermissionByUserId(paasFormDataEntityExt,userIdIn,businessType);
            case WORK_REPORT:
                //工作报告略特殊
                return checkWorkReport(paasFormDataEntityExt, userVO ,userIdIn);
            case WORK_ORDER:
                //低权限被抄送，协同负责，创建
                return checkWorkOrder(dataId, userEntity,userIdIn, paasFormDataEntityExt);
            case PRODUCT:
                return checkProduct(dataId, userEntity,userIdIn,depSet);
            case SERVICE_PROJECT:
                return checkServiceProject(dataId, userEntity, userIdIn, depSet);
            case WAREHOUSE:
                return checkWarehouse(paasFormDataEntityExt,userIdIn,depSet);
            case COMMUNICATE_PLAN:
                return checkCommunicatePlan(dataId,userIdIn,userEntity.getCorpid());
            case REIMBURSEMENT_FORM:
                return checkReimbursementForm(paasFormDataEntityExt,userEntity.getUserId());
            case EXPENSE:
                return checkExpense(paasFormDataEntityExt,userEntity.getUserId());
            case ORDER_OUTSTOCK:
                return checkPermissionByUserId(paasFormDataEntityExt,userIdIn,XbbRefTypeEnum.transferBusinessType2Index(businessType));
            case COST_ADJUST:
                return checkPermissionByUserId(paasFormDataEntityExt,userIdIn,XbbRefTypeEnum.transferBusinessType2Index(businessType));
            default:
                return false;
        }
    }

    /**
     * 其他支出单、其他收入单、资金调拨单通过系统字段‘负责人’校验
     * @param paasFormDataEntityExt
     * @param userIdIn
     * @param businessType
     * @return
     */
    private boolean checkPermissionByBelongId(PaasFormDataEntityExt paasFormDataEntityExt, List<String> userIdIn, Integer businessType){
        JSONObject data = paasFormDataEntityExt.getData();
        String userId = "";
        if (Objects.equals(businessType,XbbRefTypeEnum.OTHER_EXPENSE.getCode()) || Objects.equals(businessType,XbbRefTypeEnum.OTHER_INCOME.getCode())){
            userId = data.getString(OtherExpenseEnum.BELONG_ID.getAttr());
        }else if(Objects.equals(businessType,XbbRefTypeEnum.FUND_TRANSFER.getCode())){
            userId = data.getString(FundTransferEnum.BELONG_ID.getAttr());
        }
        return userIdIn.contains(userId);
    }

    private Boolean checkExpense(PaasFormDataEntityExt paasFormDataEntityExt, String userId) {
        JSONObject data = paasFormDataEntityExt.getData();
        String formUserCode = data.getString(ExpenseEnum.FORM_USER_CODE.getAttr());
        return Objects.equals(formUserCode, userId);
    }

    private Boolean checkReimbursementForm(PaasFormDataEntityExt paasFormDataEntityExt, String userId) {
        JSONObject data = paasFormDataEntityExt.getData();
        String formUserCode = data.getString(ReimbursementFormEnum.FORM_USER_CODE.getAttr());
        return Objects.equals(formUserCode, userId);
    }

    /**
     * 通过负责人字段
     * @param paasFormDataEntityExt
     * @param userIdIn
     * @param businessType
     * @return
     */
    private boolean checkPermissionByUserId(PaasFormDataEntityExt paasFormDataEntityExt, List<String> userIdIn, Integer businessType) {
        String userId = getOwnerId(paasFormDataEntityExt, businessType);
        if (Objects.isNull(userId)){
            return false;
        }
        return userIdIn.contains(userId);
    }

    private Boolean checkCommunicatePlan(Long dataId, List<String> userIdIn, String corpid) {
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("dataId",dataId);
        param.put("userIdIn",userIdIn);
        param.put("del",0);
        Integer count = communicatePlanUserModel.getEntitysCount(param);
        return count > 0;
    }

    private Boolean checkWarehouse(PaasFormDataEntityExt paasFormDataEntityExt ,List<String> userIdIn, Set<DepartmentVO> depSet) {
        JSONObject data = paasFormDataEntityExt.getData();
        JSONArray userIdArray;
        try {
            userIdArray = data.getJSONArray(WarehouseEnum.MANAGER_ID.getAttr());
        }catch (Exception e){
            userIdArray = new JSONArray();
        }
        if (Objects.isNull(userIdArray)) {
            userIdArray = new JSONArray();
        }
        userIdArray.retainAll(userIdIn);
        if (!userIdArray.isEmpty()){
            return true;
        }
        List<Long> depIdList;
        try {
            depIdList = JSONArray.parseArray(data.getString(WarehouseEnum.MANAGER_DEP_ID.getAttr()),Long.class);
        }catch (Exception e){
            depIdList = new ArrayList<>();
        }
        if (Objects.isNull(depIdList)) {
            depIdList = new ArrayList<>();
        }
        //仓库全公司默认有权限
        if (depIdList.contains(1L) || depIdList.contains(0L)){
            return true;
        }
        List<Long> depIdIn = new ArrayList<>();
        for (DepartmentVO departmentVO : depSet){
            depIdIn.add(departmentVO.getId());
        }
        depIdList.retainAll(depIdIn);
        return !depIdList.isEmpty();
    }

    private Boolean checkProduct(Long dataId, UserEntity userEntity, List<String> userIdIn, Set<DepartmentVO> depSet) throws XbbException {
        String corpid = userEntity.getCorpid();
        // 判断是否为子产品，如果是的话，拿下父产品id
        ProductEntityExt productEntityExt = productModel.getByKey(dataId, corpid);
        if (Objects.nonNull(productEntityExt) && Objects.nonNull(productEntityExt.getData()) && !Objects.equals(0L, productEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr()))) {
            dataId = productEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr());
        }
        List<String> depIdStrIn = new ArrayList<>();
        List<Long> depIdIn = new ArrayList<>();
        for (DepartmentVO departmentVO : depSet){
            depIdIn.add(departmentVO.getId());
        }
        List<Long> supDepIdIn = departmentModel.getSupDepIdList(userEntity.getCorpid(),depIdIn,true);
        supDepIdIn.forEach(id -> depIdStrIn.add(id.toString()));
        //数据迁移，历史原因
        depIdStrIn.add("0");
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(FieldTypeEnum.DATAID.getAlias(), dataId));
        BoolQueryBuilder userQueryBuilder = boolQuery();
        userQueryBuilder.filter(termsQuery(ProductTeamEnum.getEsAttr(ProductTeamEnum.RELATION_ID), userIdIn));
        userQueryBuilder.filter(termQuery(ProductTeamEnum.getEsAttr(ProductTeamEnum.TYPE),0));
        userQueryBuilder.filter(termQuery("del",0));
        BoolQueryBuilder depQueryBuilder = boolQuery();
        depQueryBuilder.filter(termsQuery(ProductTeamEnum.getEsAttr(ProductTeamEnum.RELATION_ID), depIdStrIn));
        depQueryBuilder.filter(termQuery(ProductTeamEnum.getEsAttr(ProductTeamEnum.TYPE),1));
        depQueryBuilder.filter(termQuery("del",0));
        BoolQueryBuilder childQueryBuilder = boolQuery();
        childQueryBuilder.should(userQueryBuilder);
        childQueryBuilder.should(depQueryBuilder);
        childQueryBuilder.minimumShouldMatch(1);
        HasChildQueryBuilder hasChildQueryBuilder = JoinQueryBuilders.hasChildQuery(IndexTypeEnum.IDX_SAAS_PRODUCT_TEAM.getType(),childQueryBuilder, ScoreMode.Max);
        boolQueryBuilder.filter(hasChildQueryBuilder);
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
        //改成count计数
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PRODUCT.getIndex());
        searchRequest.source(sourceBuilder);
        CountRequest countRequest = new CountRequest(searchRequest.indices()[0]);
        countRequest.query(searchRequest.source().query());
        long count = xbbElasticsearchRestTemplate.count(countRequest);
        return count > 0;
    }

    private Boolean checkServiceProject(Long dataId, UserEntity userEntity, List<String> userIdIn, Set<DepartmentVO> depSet) throws XbbException {
        String corpid = userEntity.getCorpid();
        List<String> depIdStrIn = new ArrayList<>();
        List<Long> depIdIn = new ArrayList<>();
        for (DepartmentVO departmentVO : depSet) {
            depIdIn.add(departmentVO.getId());
        }
        List<Long> supDepIdIn = departmentModel.getSupDepIdList(userEntity.getCorpid(), depIdIn, true);
        supDepIdIn.forEach(id -> depIdStrIn.add(id.toString()));
        //数据迁移，历史原因
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(FieldTypeEnum.DATAID.getAlias(), dataId));
        BoolQueryBuilder userQueryBuilder = boolQuery();
        userQueryBuilder.filter(termsQuery(ProductTeamEnum.getEsAttr(ProductTeamEnum.RELATION_ID), userIdIn));
        userQueryBuilder.filter(termQuery(ProductTeamEnum.getEsAttr(ProductTeamEnum.TYPE), 0));
        userQueryBuilder.filter(termQuery("del", 0));
        BoolQueryBuilder depQueryBuilder = boolQuery();
        depQueryBuilder.filter(termsQuery(ProductTeamEnum.getEsAttr(ProductTeamEnum.RELATION_ID), depIdStrIn));
        depQueryBuilder.filter(termQuery(ProductTeamEnum.getEsAttr(ProductTeamEnum.TYPE), 1));
        depQueryBuilder.filter(termQuery("del", 0));
        BoolQueryBuilder childQueryBuilder = boolQuery();
        childQueryBuilder.should(userQueryBuilder);
        childQueryBuilder.should(depQueryBuilder);
        childQueryBuilder.minimumShouldMatch(1);
        HasChildQueryBuilder hasChildQueryBuilder = JoinQueryBuilders.hasChildQuery(IndexTypeEnum.IDX_SERVICE_PROJECT_TEAM.getType(), childQueryBuilder, ScoreMode.Max);
        boolQueryBuilder.filter(hasChildQueryBuilder);
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SERVICE_PROJECT_TEAM.getType()));
        //改成count计数
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SERVICE_PROJECT.getIndex());
        searchRequest.source(sourceBuilder);
        CountRequest countRequest = new CountRequest(searchRequest.indices()[0]);
        countRequest.query(searchRequest.source().query());
        long count = xbbElasticsearchRestTemplate.count(countRequest);
        return count > 0;
    }

    private Boolean checkWorkOrder(Long dataId, UserEntity userEntity, List<String> userIdIn, PaasFormDataEntityExt paasFormDataEntityExt) {
        if (userEntity.getRoleIds().contains(RoleEnum.WORKORDER_MANAGER.getAlias())) {
            return true;
        }
//        if (userIdIn.contains(userEntity.getUserId())){
//            return true;
//        }
        if (Objects.equals(paasFormDataEntityExt.getCreatorId(), userEntity.getUserId())) {
            return true;
        }
        WorkOrderEntity workOrderEntity = workOrderModel.getByKey(dataId, userEntity.getCorpid());
        if (Objects.equals(workOrderEntity.getType(), WorkOrderTypeEnum.ROB.getCode())) {
            return true;
        }
        Integer count;
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",userEntity.getCorpid());
        param.put("del",0);
        param.put("workOrderId",dataId);
        param.put("userIdIn",userIdIn);
        count = workOrderCcModel.getEntitysCount(param);
        if (count > 0){
            return true;
        }
        count = workOrderFlowNodeModel.getEntitysCount(param);
        if (count > 0){
            return true;
        }
        param.put("dataId",dataId);
        count = workOrderFlowUserModel.getEntitysCount(param);
        return count > 0;
    }

    /**
     * 我发的,发我的,抄我的
     * @return
     */
    private Boolean checkWorkReport(PaasFormDataEntityExt paasFormDataEntityExt,UserVO userVO,List<String> userIdIn) {
        String corpid = userVO.getCorpid();
        String userId = userVO.getUserId();
        if (Objects.equals(paasFormDataEntityExt.getCreatorId(),userId)){
            return true;
        }
        if (userIdIn.contains(paasFormDataEntityExt.getCreatorId())){
            return true;
        }
        // 发我的
        Set<DepartmentVO> departmentVOSet = userVO.getDepSet();
        Set<RoleSimpleVO> roleSimpleVOSet = userVO.getRoleSet();
        List<String> deptIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<String> roleIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<String> userIds = Arrays.asList(userId);
        if (!CollectionUtils.isEmpty(departmentVOSet)){
            for (DepartmentVO item : departmentVOSet) {
                deptIdIn.add(item.getId().toString());
            }
        }
        if (!CollectionUtils.isEmpty(roleSimpleVOSet)){
            for (RoleSimpleVO item : roleSimpleVOSet) {
                roleIdIn.add(item.getId().toString());
            }
        }
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("userIdIn", CollectionUtils.isEmpty(userIds) ? null : userIds);
        param.put("deptIdIn",CollectionUtils.isEmpty(deptIdIn) ? null : deptIdIn);
        param.put("roleIdIn",CollectionUtils.isEmpty(roleIdIn) ? null : roleIdIn);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("order by", "report_id desc");
        Integer approvePeopleCount = workReportApprovePeopleModel.getEntitysCount(param);
        // 抄我的
        param.clear();
        param.put("corpid",corpid);
        param.put("reportId",paasFormDataEntityExt.getId());
        param.put("userId",userId);
        param.put("del",0);
        Integer count = workReportCcModel.getEntitysCount(param);

        return approvePeopleCount > 0 || count > 0;
    }

    public static String getOwnerId(PaasFormDataEntityExt paasFormDataEntityExt, Integer businessType) {
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        JSONObject data = paasFormDataEntityExt.getData();
        String userId;
        switch (xbbRefTypeEnum){
            case INVOICE:
            case PURCHASE_INVOICE:
                userId = paasFormDataEntityExt.getOwnerId();
                break;
            case RETURNED_PURCHASE:
//                userId = data.getString(ReturnedPurchaseEnum.MANAGER_ID.getAttr());
                userId = paasFormDataEntityExt.getOwnerId();
                break;
            case ASSEMBLE:
//                userId = data.getString(AssembleEnum.MANAGER_ID.getAttr());
                userId = paasFormDataEntityExt.getOwnerId();
                break;
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
//                userId = data.getString(InstockEnum.MANAGER_ID.getAttr());
                userId = paasFormDataEntityExt.getOwnerId();
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case ORDER_OUTSTOCK:
//                userId = data.getString(OutstockEnum.MANAGER_ID.getAttr());
                userId = paasFormDataEntityExt.getOwnerId();
                break;
            case TRANSFER:
//                userId = data.getString(TransferEnum.MANAGER_NAME.getAttr());
                userId = paasFormDataEntityExt.getOwnerId();
                break;
            case INVENTORY:
//                userId = data.getString(InventoryEnum.MANAGER_ID.getAttr());
                userId = paasFormDataEntityExt.getOwnerId();
                break;
            case CUSTOMER_COMMUNICATE:
                userId =  paasFormDataEntityExt.getCreatorId();
                break;
            case SUPPLIER_COMMUNICATE:
                userId =  paasFormDataEntityExt.getCreatorId();
                break;
            case WORK_REPORT:
                userId = paasFormDataEntityExt.getCreatorId();
                break;
            case COST_ADJUST:
                userId = paasFormDataEntityExt.getOwnerId();
                break;
            default:
                userId = paasFormDataEntityExt.getOwnerId();
                break;
        }
        return userId;
    }

    /**
     * 有团队的详情权限校验
     * @param businessType
     * @return
     */
    private Boolean checkPermissionByTeam(Integer businessType, BoolQueryBuilder boolQueryBuilder, String corpid) throws XbbException {
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        IndexTypeEnum indexTypeEnum;
        switch (xbbRefTypeEnum){
            case CUSTOMER_MANAGEMENT:
            case DISTRIBUTOR_MANAGEMENT:
                indexTypeEnum = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
                break;
            case CONTRACT:
            case ORDER:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_CONTRACT_TEAM;
                break;
            case SALES_OPPORTUNITY:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_OPPORTUNITY_TEAM;
                break;
            case CONTACT:
            case DISTRIBUTOR_CONTACT:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_CONTACT_TEAM;
                break;
            case REFUND:
            case RETURN:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_REFUND_TEAM;
                break;
            case PAYMENT:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM;
                break;
            case PAY_PLAN:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM;
                break;
            case SUPPLIER:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM;
                break;
            case SUPPLIER_CONTACT:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_TEAM;
                break;
            case PURCHASE:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM;
                break;
            case BOM_BILL:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_BOM_TEAM;
                break;
            case PRODUCTION_ORDER:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER_TEAM;
                break;
            case QUOTATION:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_QUOTATION_TEAM;
                break;
            case PAYMENT_SHEET:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM;
                break;
            case PAY_SHEET:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM;
                break;
            case PAYMENT_TASK:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_PAYMENT_TASK_TEAM;
                break;
            case CLUE:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_CLUE_TEAM;
                break;
            case MARKET_ACTIVITY:
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY_TEAM;
                break;
            default:
                return false;
        }
        ElasticAggsPojo elasticAggsPojo = esHelper.elasticAggs(indexTypeEnum, boolQueryBuilder, null);
        return StringUtil.toInt(elasticAggsPojo.getTotal(), 0) > 0;
    }

    /**
     * 包装查询参数
     *
     * @param dataId 数据id
     * @param userIdIn 员工idIn
     * @param corpid 公司id
     * @param indexTypeEnum
     * @return org.elasticsearch.index.query.BoolQueryBuilder
     * @author 徐俊杰
     * @date 2019/7/4 11:08
     * @since v1.0
     */
    private BoolQueryBuilder permissionQuery(Long dataId, List<String> userIdIn, String corpid, IndexTypeEnum indexTypeEnum) {
        return ElasticSearchConditionUtil.permissionQuery(dataId, userIdIn, corpid, indexTypeEnum);
    }

    /**
     * 包装查询参数（包含负责人）
     *
     * @param dataId 数据id
     * @param userIdIn 员工idIn
     * @param corpid 公司id
     * @param indexTypeEnum
     * @return org.elasticsearch.index.query.BoolQueryBuilder
     * @author 徐俊杰
     * @date 2019/7/4 11:08
     * @since v1.0
     */
    private BoolQueryBuilder permissionQueryIsMain(Long dataId, List<String> userIdIn, String corpid, IndexTypeEnum indexTypeEnum) {
        return ElasticSearchConditionUtil.permissionQueryIsMain(dataId, userIdIn, corpid, indexTypeEnum);
    }

    /**
     * 公海校验
     * @param userEntity
     * @param dataId
     * @param businessType
     * @return
     * @throws XbbException
     */
    private Boolean publicCustomerCheck(UserEntity userEntity,Long dataId,Long formId, Integer businessType) throws XbbException {
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(userEntity,userVO);
        return publicCustomerCheck(userVO, dataId, formId, businessType);
    }

    /**
     * 单据是否非法
     * 删除什么的
     * @param paasFormDataEntityExt
     * @param subBusinessType
     * @return
     */
    public boolean checkData(PaasFormDataEntityExt paasFormDataEntityExt, Integer subBusinessType) throws XbbException{
        return checkCrmData(paasFormDataEntityExt, subBusinessType);
    }


    private boolean checkCrmData(PaasFormDataEntityExt paasFormDataEntityExt, Integer subBusinessType) throws XbbException {
        if (Objects.isNull(paasFormDataEntityExt)){
            return true;
        }
        boolean recycle = (Objects.equals(subBusinessType, XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode()) || Objects.equals(subBusinessType,XbbRefTypeEnum.CLUE_RECYCLE.getCode()) && Objects.equals(paasFormDataEntityExt.getDel(), DelEnum.DELETE.getDel()));
        if (recycle){
            // 客户回收站和线索回收站的单据del都是1
            return false;
        }
        if (Objects.equals(paasFormDataEntityExt.getDel(),DelEnum.DELETE.getDel()) || Objects.equals(paasFormDataEntityExt.getDel(), DelEnum.REMOVE_COMPLETELY.getDel())){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);
        }
        return false;
    }

    public boolean mainUser(Integer businessType, String userId, Long dataId, String corpid) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery("userId.keyword",userId));
        boolQueryBuilder.filter(termQuery("isMain",1));
        boolQueryBuilder.filter(termQuery("dataId",dataId));
        return checkPermissionByTeam(businessType, boolQueryBuilder, corpid);
    }

    public Boolean publicCustomerCheck(UserVO userVO, Long dataId, Long formId, Integer businessType) throws XbbException {
        String corpid = userVO.getCorpid();
        ConditionListPojo conditionListPojo = new ConditionListPojo(corpid, formId, businessType, null, null, new ArrayList<>(), new ArrayList<>(), userVO, null, null, null, null, null);
        GroupConditionPoJo groupConditionPoJo = publicGroupHelp.getPublicGroup(conditionListPojo);
        PaasListGroupEntity paasListGroupEntity = groupConditionPoJo.getPaasListGroupEntity();
        // 地址查询条件封装
        AddressUtil.addressSearchShouldCondition(groupConditionPoJo.getShouldConditionList());
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(FieldTypeEnum.DATAID.getAlias(), dataId));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        List<ConditionsEntityExt> listGroupConditionList = JSONArray.parseArray(paasListGroupEntity.getJsonData(), ConditionsEntityExt.class);
        if (!Objects.isNull(listGroupConditionList) && !listGroupConditionList.isEmpty()){
            EsUtil.parseCondition(boolQueryBuilder,listGroupConditionList,"",corpid,businessType);
        }
        if (!Objects.isNull(conditionListPojo.getShouldConditionList()) && !conditionListPojo.getShouldConditionList().isEmpty()){
            EsUtil.parseShouldCondition(boolQueryBuilder,conditionListPojo.getShouldConditionList(),"",corpid,businessType);
        }
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(userVO.getCorpid(), businessType, SaasMarkEnum.SAAS.getCode());
        ElasticAggsPojo elasticAggsPojo = esHelper.elasticAggs(indexTypeEnum, boolQueryBuilder, null);
        return StringUtil.toInt(elasticAggsPojo.getTotal(), 0) > 0;
    }



    private boolean paasCheckPermission(UserVO userVO, Long dataId, Long menuId) throws XbbException {
        if (userVO.isAdminOrBoss()) {
            return true;
        }
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(userVO, userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.PAAS, null, menuId);
        if (Objects.equals(dataPermission, DataPermissionEnum.ALL.getCode())) {
            return true;
        }
        List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, userVO.getUserId(), userVO.getCorpid(), BasicConstant.ZERO,false);
        IndexTypeEnum indexTypeEnum = IndexTypeEnum.IDX_FORM_DATA_TEAM;
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", userVO.getCorpid()));
        boolQueryBuilder.filter(termQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(indexTypeEnum, FieldTypeEnum.DATAID.getAlias()), dataId));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(indexTypeEnum, ParameterConstant.USER_ID), userIdIn));
        ElasticAggsPojo elasticAggsPojo = esHelper.elasticAggs(indexTypeEnum, boolQueryBuilder, null);
        return StringUtil.toInt(elasticAggsPojo.getTotal(), 0) > 0;
    }

    /**
     * 移除校验格式化的数据
     *
     * @param data
     */
    public void removeConvertedData(JSONObject data){
        data.keySet().removeIf(next -> next.contains(FieldTypeEnum.SUB_FORM.getEsalias()) && next.contains(StringConstant.POINT));
    }
}
